import jsonp from 'common/js/jsonp.js'
import { commonParams, options, ERR_OK } from './config'
import axios from 'axios'

// ?g_tk=2112862036&uin=305611672&format=json&inCharset=utf-8&outCharset=utf-8&notice=0&platform=h5&needNewCode=1&_=1543292863131

export function getRecommend() {
  const url = 'https://c.y.qq.com/musichall/fcgi-bin/fcg_yqqhomepagerecommend.fcg'
  let params = Object.assign({}, commonParams, {
    uin: 0,
    platform: 'h5',
    needNewCode: 1
  })
  return jsonp(url, params, options)
}

export function getDissList() {
  // const url = 'https://c.y.qq.com/splcloud/fcgi-bin/fcg_get_diss_by_tag.fcg'
  let params = Object.assign({}, commonParams, {
    picmid: 1,
    rnd: Math.random(),
    // g_tk: 1202883834,
    // jsonpCallback: 'getPlaylist',
    loginUin: 0,
    hostUin: 0,
    format: 'json', // format: 'jsonp'
    inCharset: 'utf8',
    outCharset: 'utf-8',
    notice: 0,
    platform: 'yqq',
    needNewCode: 0,
    categoryId: 10000000,
    sortId: 5,
    sin: 0,
    ein: 29
  })
  // return jsonp(url, params, options)
  return axios.get('/apimusic/qqyydiss', {
    params: params
  })
}

// 获取歌单列表
export function getcdinfo(disstid) {
  let params = Object.assign({}, commonParams, {
    type: 1,
    json: 1,
    utf8: 1,
    onlysong: 0,
    disstid: disstid,
    format: 'jsonp',
    g_tk: 1819849191,
    loginUin: 0,
    hostUin: 0,
    notice: 0,
    platform: 'yqq',
    needNewCode: 0
  })
  // return new Promise( )
  return new Promise(function (resolve, reject) {
    // let reg = /^\w+\(({[^()]+})\)$/
    let reg = /^\w+\(({.+})\)$/
    axios.get('/apimusic/getcdinfo', {
      params: params
    }).then((resp) => {
      let ret = resp.data
      let matches = null
      if (typeof ret === 'string') {
        matches = ret.match(reg)
        if (matches) {
          ret = JSON.parse(matches[1])
        }
      }
      if (ret.code === ERR_OK) {
        resolve(ret.cdlist[0]) // ret.cdlist[0].songlist
      } else {
        reject(Error('获取歌单数据失败'))
      }
    }).catch(() => {
      reject(Error('获取歌单数据失败'))
    })
  })
}
